package com.ruicar.afs.cloud.demo.demo.withoutpass;

import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.holder.TransRequestContextHolder;
import com.ruicar.afs.cloud.common.core.security.feign.Oauth2OperationService;
import com.ruicar.afs.cloud.common.core.security.service.AfsNoPassLoginService;
import com.ruicar.afs.cloud.common.core.security.util.AfsPublicTokenUtil;
import com.ruicar.afs.cloud.common.core.util.Base64Util;
import com.ruicar.afs.cloud.common.core.util.ClientTypeUtil;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/system")
@AllArgsConstructor
//在gateway 和应用里配置 非授权调用
public class WithOutPassLoginController {
    private final Oauth2OperationService oauth2OperationService;
    private final AfsNoPassLoginService afsNoPassLoginService;
    @PostMapping("/login")
    IResponse<Object> loginWithOutPass(@RequestParam String userName){
        //构建 http请求参数
        Map<String, String> requestParam = new HashMap<>(8);
        requestParam.put(CommonConstants.GRANT_TYPE, "password");
        //用户名为前缀+系统登录名
        requestParam.put(CommonConstants.USERNAME, CommonConstants.WITH_OUT_PASS_PREFIX+userName);
        //密码填系统默认密码
        requestParam.put(CommonConstants.PASSWORD, CommonConstants.DEFAULT_PASS);
        requestParam.put(CommonConstants.TENANT_ID, CommonConstants.DEFAULT_PASS);
        //填充一次性校验码，使用过后不能再次使用,校验码有效期为 120s
        requestParam.put(CommonConstants.NO_PASS_LOGIN,afsNoPassLoginService.getCheckCode());
        //构建 http请求头
        Map<String, String> requestHeader = new HashMap<>(8);
        ClientTypeUtil.ClientTypeEnum clientTypeEnum = TransRequestContextHolder.getClientInfo().getClientType();
        requestHeader.put(CommonConstants.AUTHORIZATION, "Basic " + Base64Util.encode((clientTypeEnum.getClientId()+ ":" + clientTypeEnum.getClientSecret()).getBytes()));
        return IResponse.decode(oauth2OperationService.login(requestParam,requestHeader));
    }

    @PostMapping("/publicToken")
    IResponse<Object> publicToken(){
       return IResponse.success(AfsPublicTokenUtil.getPublicToken());
    }

}
